﻿<template>
  <div class="Login">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="rules"
      label-width="100px"
      class="login-form"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" />
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button type="text" @click="forgotPassword">忘记密码？</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="Login">
import { ref } from 'vue';
import { useRouter } from 'vue-router'; 
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { ElForm } from 'element-plus'; 
// 定义表单数据类型
interface LoginForm {
  username: string;
  password: string;
  rememberMe: boolean;
}

// 定义登录响应类型
interface LoginResponse {
  sha1?: string;
  message?: string;
}

// 路由实例
const router = useRouter();

// 表单的状态
const loginForm = ref<LoginForm>({
  username: '',
  password: '',
  rememberMe: false,
});

// 表单验证规则
const rules = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
});

// 表单引用
const loginFormRef = ref<InstanceType<typeof ElForm> | null>(null);

// 登录请求函数
const onSubmit = async () => {
  try {
    // 调用表单验证
    if (!loginFormRef.value) return;
    await loginFormRef.value.validate();

    // 发送登录请求
    const response = await axios.post<LoginResponse>(`${window.location.protocol}//${window.location.hostname}/api/login`, {
      username: loginForm.value.username,
      password: loginForm.value.password,
    });

    // 登录成功
    if (response.data.sha1) {
      // 保存 token 到本地存储或 cookies
      localStorage.setItem('authToken', response.data.sha1);
      
      // 如果勾选了"记住我"，可以额外保存用户信息
      if (loginForm.value.rememberMe) {
        localStorage.setItem('rememberMe', loginForm.value.username);
      }

      // 成功消息提示
      ElMessage.success('登录成功！');
      
      // 这里可以做页面跳转，例如跳转到首页
      router.push('/');
    } else {
      // 处理登录失败
      ElMessage.error(response.data.message || '登录失败，请检查用户名或密码');
    }
  } catch (error) {
    ElMessage.error('请求失败，请稍后再试');
  }
};

// 忘记密码函数 (根据需求自定义)
const forgotPassword = () => {
  ElMessage.info('请联系管理员重置密码');
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  background-color: rgb(50, 50, 64);
}
</style>
